package com.dd.ent.car.service.note;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.dd.ent.car.common.bean.User;
import com.dd.ent.car.common.bean.note.Note;
import com.dd.ent.car.common.config.UIConfig;
import com.dd.ent.car.common.config.UrlConfig;
import com.dd.ent.car.common.dao.NoteDao;
import com.dd.ent.car.service.BaseService;
import com.pp.ent.base.log.MLog;
import com.pp.ent.core.manage.ServiceHandler;
import com.pp.ent.db.DbResult;
import com.pp.ent.view.annotation.Inject;
import com.qiniu.android.common.Zone;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCancellationSignal;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;
import com.qiniu.util.Auth;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by spring on 2017/3/16.
 */

public class NoteService extends BaseService {
    @Inject
    private NoteDao noteDao;


    public void saveNoteDb(Note note) {
        noteDao.insertNote(note);
    }


    /**
     * 从db中找到所有的贴，也就是草稿
     */
    public void queryDbNote() {
        noteDao.queryAllNote();
    }

    public void sumbitNote(Note note,String uid) {
        Map<String, String> parms = new HashMap<>();
        parms.put("uid", uid);
        parms.put("uuid",note.getUuid()==null?"":note.getUuid());
        parms.put("title", note.getTitle());
        parms.put("content", note.getContent());
        parms.put("bgColor", note.getBgColor());
        parms.put("createTime", note.getCreateTime());
        parms.put("updateTime", note.getUpdateTime());
        parms.put("type", String.valueOf(note.getType()));
        parms.put("isEncrypt", String.valueOf(note.getIsEncrypt()));
        post(UrlConfig.POST_NOTE_INFO, parms, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                notifyUI(UIConfig.ADD_NOTE_INFO_TO_SERVER_SUCCESS);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                notifyUI(UIConfig.ADD_NOTE_INFO_TO_SERVER_FAIL);
            }
        });
    }


    public void getVideoByUid(String uid) {
        String url = UrlConfig.GET_NOTE_INFO_BY_UID + "uid=" + uid;
        get(url, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                notifyUI(UIConfig.GET_NOTE_INFO_BY_UID_SUCCESS, response == null ? null : response.toString());
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                MLog.error(TAG, error);
                notifyUI(UIConfig.GET_NOTE_INFO_BY_UID_FAIL);
            }
        });
    }

    public ResponseInfo syncSumbitFile(String filePath) {
        String accessKey = "RtVQakqLfN1NBlr2HStgxEb4YM-UuymeNo4ABB_Z";
        String secretKey = "sj0_fTi3pWMawIEkvcKqzWp_vkC79O_fRLNsbWPB";
        String bucket = "dengqu";
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);

        MLog.debug(TAG, "upToken =" + upToken);

        Configuration config = new Configuration.Builder()
                .chunkSize(256 * 1024)  //分片上传时，每片的大小。 默认256K
                .putThreshhold(512 * 1024)  // 启用分片上传阀值。默认512K
                .connectTimeout(10) // 链接超时。默认10秒
                .responseTimeout(60) // 服务器响应超时。默认60秒
                //.recorder(recorder)  // recorder分片上传时，已上传片记录器。默认null
                // .recorder(recorder, keyGen)  // keyGen 分片上传时，生成标识符，用于片记录器区分是那个文件的上传记录
               // .zone(Zone.zone2) // 设置区域，指定不同区域的上传域名、备用域名、备用IP。
                .build();
        // 重用uploadManager。一般地，只需要创建一个uploadManager对象
        UploadManager uploadManager = new UploadManager(config);
        return uploadManager.syncPut(filePath, null, upToken, new UploadOptions(null
                , null, false, new UpProgressHandler() {
            @Override
            public void progress(String key, double percent) {
                MLog.debug(TAG, "key=" + key + ",percent=" + percent);
                notifyUI(UIConfig.UPLOAD_VIDEO_QI_NIU_PROGRESS_RESPONSE, key, percent);
            }
        }, new UpCancellationSignal() {
            @Override
            public boolean isCancelled() {
                return false;
            }
        }));
    }

    public void sumbitPlayCountToNote(String noteId, long addVisitCount) {
        Map<String, String> params = new HashMap<>();
        params.put("noteId", noteId);
        params.put("addVisitCount", String.valueOf(addVisitCount));
        post(UrlConfig.ADD_VISIT_NOTE_COUNT, params, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                MLog.info(TAG,"sumbitPlayCountToNote onResponse response="+response);
                notifyUI(UIConfig.ADD_PLAY_COUNT_TO_NOTE_SUCCESS);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                MLog.info(TAG,"sumbitPlayCountToNote onErrorResponse error="+error);
                MLog.error(TAG, error);
                notifyUI(UIConfig.ADD_PLAY_COUNT_TO_NOTE_FAIL);
            }
        });
    }

    @ServiceHandler("query_all_note")
    public void queryALlNote(DbResult dbResult) {
        List<Note> users = null;
        if (dbResult == null || !dbResult.isSuccessful()) {
        } else {
            users = (List<Note>) dbResult.data;
        }
        notifyUI("query_all_note_reponse", users);
    }

}
